package mvc.gui.impl.mainframe;

import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.JOptionPane;

import mvc.core.IMachuPicchu;
import mvc.gui.utils.ImagePanel;
import mvc.image.MachuImage;

public class MainFramePresenter implements PropertyChangeListener,
		ComponentListener {

	private MainFrame panel;
	private IMachuPicchu machu;
	private BufferedImage mainStageImage;
	private ImagePanel mainStage;

	public MainFramePresenter(IMachuPicchu machuPicchu, MainFrame frame) {
		this.machu = machuPicchu;
		this.panel = frame;
		machu.addPropertyChangeListener(this);
		panel.addComponentListener(this);
		mainStage = panel.getMainStage();
	}

	/**
	 * Updates the image displayed on mainStage with new MachuImage.
	 * 
	 * @param mi
	 */
	private void updateImage(MachuImage mi) {
		mainStageImage = null;
		mainStageImage = (BufferedImage) machu.processImage(mi, -1, -1);
		repaintMainStage();
	}

	/*
	 * Repaints mainStage.
	 */
	private void repaintMainStage() {
		int width, height;

		if ((double) mainStage.getWidth() / (double) mainStage.getHeight() < (double) mainStageImage
				.getWidth()
				/ (double) mainStageImage.getHeight()) {
			height = -1;
			width = mainStage.getWidth();
		} else {
			width = -1;
			height = mainStage.getHeight();
		}

		mainStage.setImage(machu.getScaledImage(mainStageImage, width, height));

		mainStage.revalidate();
		panel.repaint();
	}

	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if (evt.getPropertyName().equals("selectedImagesChanged")) { //$NON-NLS-1$
			if (machu.getImageList().size() > 0) {
				updateImage(machu.getSelectedImages().get(0));
			} else {
				mainStage.setImage(null);
				mainStage.revalidate();
				panel.repaint();

			}
		}
		if (evt.getPropertyName().equals("errorDialog")) { //$NON-NLS-1$
			JOptionPane.showMessageDialog(null, evt.getNewValue().toString(),
					"Machu Picchu", JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$

		}

	}

	@Override
	public void componentResized(ComponentEvent e) {
		if (machu.getImageList().size() > 0) {
			repaintMainStage();
		} else {
			mainStage.setImage(null);
			mainStage.revalidate();
			panel.repaint();

		}
	}

	@Override
	public void componentHidden(ComponentEvent e) {
		// Added since this class is a ComponentListener
	}

	@Override
	public void componentMoved(ComponentEvent e) {
		// Added since this class is a ComponentListener
	}

	@Override
	public void componentShown(ComponentEvent e) {
		// Added since this class is a ComponentListener
	}

}
